import ResMgr from "../../../Framework/Res/ResMgr";
export class NodePool {
    //用于存储对象的节点
    //对象池
    private _pool: cc.NodePool = null;
    //对象池的大小
    private _poolSize: number = null;
    //需要实例化的预制体
    private _prefab: cc.Prefab = null;
    //在创建这个类的对象时，创建对象池
    constructor(name: string, poolSize: number = 10) {
        this._poolSize = poolSize;
        //创建一个对象
        this.createNodePool(name);
    }

    createNodePool(name: string) {
        this._pool = new cc.NodePool();
        //获取预制体资源
        this._prefab = ResMgr.instance.getRes<cc.Prefab>("Game", name);
        if (!this._prefab) {
            cc.error(name + "预制体不存在");
        }
        //实例化
        for (let i = 0; i < this._poolSize; i++) {
            let node = cc.instantiate(this._prefab);
            this._pool.put(node);
        }
    }
    //获取节点
    getNode() {
        //如果对象池中没有节点，就实例化节点
        if (this._pool.size() <= 0) {
            let node = cc.instantiate(this._prefab);
            return node;
        }
        return this._pool.get();
    }
    //向对象池中存入节点
    putNode(node: cc.Node) {
        //如果对象池中满了，就将节点进行销毁
        if (this._pool.size() >= this._poolSize) {
            node.destroy();
            return;
        }
        this._pool.put(node);
    }
    //清空对象池
    clearPool() {
        this._pool.clear();
    }
}


export class PoolManager {
    //用于管理对象池
    //使用单例模式
    private static _instance: PoolManager = null;
    static get instance() {
        if (!this._instance) {
            this._instance = new PoolManager();
        }
        return this._instance;
    }
    private _poolMap: Map<string, NodePool> = new Map();
    constructor() { }
    //获取对象池
    getNodePool(name: string) {
        if (name.length <= 0 || !name) {
            return null;
        }
        let pool = this._poolMap.get(name);
        if (!pool) {
            //如果没有就创建
            pool = new NodePool(name);
            this._poolMap.set(name, pool);
        }
        return pool;
    }

    //清空所有对象池
    clearPoolMap() {
        for (let poolName in this._poolMap) {
            let pool = this._poolMap.get(poolName);
            pool.clearPool();
        }
        this._poolMap.clear();
    }


}
